package com.ljy.jymail.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;



@Configuration
public class MyRabbitMqConfig {

    /*
     * 当第一次监听rabbitMq时才会在rabbitMq中创建队列
     * */



    /*使用JSON序列化机制，进行消息转换，rabbitMq发送的所有消息都是json的*/
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    /*
    * 创建交换机--库存服务的默认交换机
    *
    * */
    @Bean
    public Exchange stockEventExchange(){
        /*
        * String name, boolean durable, boolean autoDelete, Map<String, Object> arguments
        * */
        return new TopicExchange("stock-event-exchange",true,false);
    }

    @Bean
    public Queue stockReleaseStockQueue(){
        return new Queue("stock.release.stock.queue",true,false,false);
    }

    /*
    * 延迟队列
    * */
    @Bean
    public Queue stockDelayQueue(){
        //x-dead-Letter-exchange: order-event-exchange 死信路由
        //x-dead-Letter-routing-key: order.release.order 死信路由键
        //x-message-ttl: 60000

        Map<String, Object> arguments = new HashMap<String, Object>();
        arguments.put("x-dead-letter-exchange","stock-event-exchange");//死亡后发送到哪个虚拟机
        arguments.put("x-dead-letter-routing-key","stock.release");//死亡后的路由键
        arguments.put("x-message-ttl",120000); //存活时间
        Queue queue = new Queue("stock.delay.queue", true, false, false,arguments);
        return queue;
    }

    @Bean
    public Binding stockReleaseBinding(){
        /*
        * String destination 队列,  Binding.DestinationType destinationType 类型,
        * String exchange 交换机 , String routingKey 路由键 , @Nullable Map<String, Object> arguments 参数
        * */

        return new Binding("stock.release.stock.queue", Binding.DestinationType.QUEUE,
                "stock-event-exchange","stock.release.#",null
        );
    }

    @Bean
    public Binding stockLockBinding(){
        /*
         * String destination 队列,  Binding.DestinationType destinationType 类型,
         * String exchange 交换机 , String routingKey 路由键 , @Nullable Map<String, Object> arguments 参数
         * */

        return new Binding("stock.delay.queue", Binding.DestinationType.QUEUE,
                "stock-event-exchange","stock.locked",null
        );
    }
}
